package cn.willbj.brief.hd.util.demo;

import java.util.UUID;

/**
 * 附件UUID生成器
 * @author zhangfeng
 * @date 2016年5月3日
 */
public class AttachUUIDGenerator {
	
	private final static char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
		'9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
		'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
		'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
		'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',
		'Z', '-', '_'};
	
	private final static String[] hexStr = {"0000" ,"0001", "0010", "0011", "0100","0101","0110","0111","1000","1001", "1010", "1011", "1100", "1101", "1110", "1111"};

	/**
	 * 支持的最大进制数
	 */
	private static final int MAX_RADIX = digits.length;
	
	/**
	 * 支持的最小进制数
	 */
	private static final int MIN_RADIX = 2;
	
	/**
	 * 生成随机UUID字符串
	 * @return 
	 * @author zhangfeng
	 * @date 2016年5月3日
	 */
	public static String randomUUID() {
		String attachDataUUID = UUID.randomUUID().toString();
		attachDataUUID = attachDataUUID.replace("-", "");
		attachDataUUID = change(toBinary(attachDataUUID));
		return attachDataUUID;
	}
	
	/**
	 * 将2进制字符串转换为10进制
	 * 
	 * @param 二进制字符串
	 * @return
	 */
	private static String change(String binaryString) {
		String rtn = "";
		int len = binaryString.length();
		int count = len/6;
		for(int i = 0; i < count; i++){
			String tmp = binaryString.substring(i*6, (i+1)*6);
			rtn = rtn + toString(Integer.valueOf(tmp, 2),64);
		}
		for(int j = 0;j < 7; j++){
			int a = (int)(Math.random()*64);
			rtn = rtn + digits[a];
		}
		return rtn;
	}
	
	/**
	 * 将长整型数值转换为指定的进制数（最大支持64进制，字母数字已经用尽）
	 * 
	 * @param i
	 * @param radix
	 * @return
	 */
	private static String toString(long i, int radix) {
		if (radix < MIN_RADIX || radix > MAX_RADIX)
			radix = 10;
		if (radix == 10)
			return Long.toString(i);
		final int size = 68;
		int charPos = 67;
		char[] buf = new char[size];
		boolean negative = (i < 0);

		if (!negative) {
			i = -i;
		}
		while (i <= -radix) {
			buf[charPos--] = digits[(int) (-(i % radix))];
			i = i / radix;
		}
		buf[charPos] = digits[(int) (-i)];
		return new String(buf, charPos, (size - charPos));
	}
	
	/**
	 * 将16进制字符串转换为2进制字符串
	 * 
	 * @param i
	 * @param radix
	 * @return
	 */
	private static String toBinary(String hexString) {
		String rtn = "";
		int len = hexString.length();
		for(int i = 0; i < len; i++){
			String single = hexString.charAt(i)+"";
			int singleint=Integer.parseInt(single,16);
			String singlebin=hexStr[singleint];
			//Integer.toBinaryString(singleint);
			rtn = rtn + singlebin;
		}
		return rtn;
	}
}
